require 'rubygems'
require 'postgres'
require 'erb'

class DatabaseSchemaProvider

    def initialize(connection_string)
        @conn_str = connection_string
    end
    
    def get_table_columns() 
        resultset = execute_sql(get_column_metadata_sql)
        get_columns_from_dataset(resultset)
    end
    
    private
    
    def get_column_metadata_sql
        <<-SQL
        select column_name, data_type from information_schema.columns 
        where table_catalog='#{@conn_str[:catalog]}' 
        and table_schema='#{@conn_str[:schema]}' and table_name='#{@conn_str[:table_name]}'
        SQL
    end
    
    def get_columns_from_dataset(resultset)
        columns=[]
        resultset.each do |row|
            columns.push(row[0])
        end
        columns
    end
    
    def connect_db
        begin
            conn = PGconn.new(@conn_str[:database], @conn_str[:port], 
                nil, nil , @conn_str[:catalog], @conn_str[:user], @conn_str[:password])
            yield conn if conn
            conn.close
        rescue PGError => err
            p "Exception:", err
        end 
    end
    
    def execute_sql(sql)
        resultset = nil
        connect_db do |conn| 
            resultset = conn.query(sql)
        end
        return resultset
    end
end

class Template
    def initialize(template_path, schema_provider)
        @template = template_path
        @schema_provider = schema_provider
    end
    
    def generate
        res = nil
        File.open(@template) do |file|
            cols = @schema_provider.get_table_columns
            erb = ERB.new(file.read)
            res = erb.result(binding)   
        end
        return res
    end
end

connection_settings = {
    :catalog => 'cirrus_development',
    :port => 5432,
    :schema => 'public',
    :user => 'nauman',
    :password => '',
    :table_name => 'customers'
}
template_path = "#{File.dirname(__FILE__)}/class_template.erb"
t = Template.new(template_path, DatabaseSchemaProvider.new(connection_settings))
puts t.generate
